package com.bothin.experiment4.service.impl;

import com.bothin.experiment4.constant.NoticeNumConstant;
import com.bothin.experiment4.enums.ResultEnum;
import com.bothin.experiment4.exception.SellException;
import com.bothin.experiment4.model.Notice;
import com.bothin.experiment4.model.Product;
import com.bothin.experiment4.service.IProductService;
import com.bothin.experiment4.service.base.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by bothin
 * At 2019/12/17 9:22
 * Description:
 */
@Service
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService {
    @Override
    public Product findById(Object id) {
        return productMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Product> findAll() {
        return productMapper.selectAll();
    }

    @Override
    @Transactional
    public void deleteById(Object id) {
        productMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional
    public void update(Product product) {
        productMapper.updateByPrimaryKeySelective(product);
    }

    @Override
    @Transactional
    public void insert(Product product) {
        productMapper.insert(product);
    }

    @Override
    public Integer selectPriceByProductId(String productId) {
        return productMapper.selectPriceByProductId(productId);
    }

    @Override
    public List<Product> findByKeyword(String key) {
        return productMapper.findByKeyword("%"+key+"%");
    }

    @Override
    @Transactional
    public void increaseStock(String id,Integer num) {
        Product product = findById(id);
        if (product==null){
            throw new SellException(ResultEnum.PRODUCT_NOT_EXIST,"/stockman/manage/out/list");
        }
        Integer res = product.getProductStock() + num;
        product.setProductStock(res);
        update(product);
    }

    /**
     * //返回库存与阈值的差值
     * @param id
     * @param num
     * @return
     */
    @Override
    @Transactional
    public int decreaseStock(String id,Integer num) {
        Product product = findById(id);
        if (product==null){
            throw new SellException(ResultEnum.PRODUCT_NOT_EXIST,"/stockman/manage/out/list");
        }
        Notice notice = noticeMapper.selectByPrimaryKey(NoticeNumConstant.NOTICE_NUM_ID);
        int notice_num = 0;
        if (notice!=null)
            notice_num = notice.getNoticeNum();
        int res = product.getProductStock() - num;
        if (res < notice_num) {
            //返回库存与阈值的差值
            return res - notice_num;
        }
        product.setProductStock(res);
        update(product);
        return 0;
    }
}
